package com.iwhalecloud.bss.kite.cucc.web.controller.order;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.order.ICommonSevice;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IOrderService;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderInfo;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderInfoListReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.OrderListInfo;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.order.PropertyValueVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr.PersonAttrDealService;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.transaction.KiteTransactional;
import com.iwhalecloud.bss.kite.service.util.CopyToDtoUtil;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <Description> 公共信息处理 <br>
 *
 * @author huang.caibiao<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2019-05-08 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.web.controller.order <br>
 */
@RestController
@RequestMapping("/localCommonAttr")
@Api(tags = {
    "/localCommonAttr - 公共信息"
})
public class LocalCommonAttrController {
    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOrderService orderService;
    @Autowired
    private ICommonSevice commonService;

    @Autowired
    private PersonAttrDealService personAttrDealService;

    @KiteTransactional
    @ApiOperation(value = "获取起租信息属性", notes = "获取起租信息属性" )
    @PostMapping( {"/getOrderStartRentAttrs"})
    public DataResult<List<KiteAttr>> getOrderStartRentAttrs(@RequestParam String moduleId, @RequestParam(required = false) String sceneInstId) {

        List<KiteAttr> kiteAttrs = querySceneInstService.listCommonAttrsByModuleId(sceneInstId, moduleId)
            .stream().filter(kiteAttr ->!KiteStringUtils.isEqual("H", kiteAttr.getShowType())&& !KiteStringUtils.isEqual("1", kiteAttr.getObjId()))
            .collect(Collectors.toList());
        // 上海五大双线 订购、变更时的起租 起租时间默认展示报竣时间，可修改。
        String bizType = querySceneInstService.getExtParameterValue(sceneInstId, "bizType");
        String postProvinceNbr = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        String serialNumber = querySceneInstService.getCommonAttrValue(sceneInstId, "business_number");
        if (KiteListUtils.isNotEmpty(kiteAttrs)) {
            for (KiteAttr kiteAttr : kiteAttrs) {
                if (KiteStringUtils.equals("REC_10057", kiteAttr.getFieldName())
                    && KiteStringUtils.equals(LocalKeyConsts.PROVINCE_SHANGHAI, postProvinceNbr)
                    && KiteStringUtils.isEmpty(kiteAttr.getValue())) {
                    OrderInfoListReq orderInfoListReq = new OrderInfoListReq();
                    orderInfoListReq.setQueryType("order");
                    orderInfoListReq.setPage("1");
                    orderInfoListReq.setSize("20");
                    OrderInfoReq order = new OrderInfoReq();
                    order.setSerialNumber(serialNumber);
                    order.setBizType(bizType);
                    order.setOrderId(querySceneInstService.getExtParameterValue(sceneInstId, "outOrderId"));
                    orderInfoListReq.setOrder(order);
                    // 调政企订单列表查询接口获取OSS竣工时间
                    OrderListInfo orderListInfo = orderService.queryOrderList(orderInfoListReq);
                    if (orderListInfo == null || !KiteStringUtils.equals(orderListInfo.getCode(), "00000")) {
                        ErrorConsts.INF_INVOKE_ERROR
                            .throwOut(LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), "获取政企订单列表查询接口失败！", "");
                    }
                    List<OrderInfo> orderInfoList = orderListInfo.getOrderInfoList();
                    if (KiteListUtils.isNotEmpty(orderInfoList)) {
                        for (OrderInfo orderInfo : orderInfoList) {
                            kiteAttr.setValue(orderInfo.getOssCompleteDate() == null ? "" : orderInfo.getOssCompleteDate());
                            kiteAttr.setValueDesc(orderInfo.getOssCompleteDate() == null ? "" : orderInfo.getOssCompleteDate());
                        }
                    }
                }
                personAttrDealService
                    .apply(KiteWebContext.getContext().getCurrentSceneInstId(), kiteAttr.getFieldName(),
                        kiteAttr.getValue(), kiteAttr.getValueDesc(), moduleId);
            }
        }

        // 批量起租重提详情页面，起租属性置灰
        if (Objects.nonNull(
            SpringUtil.getBean(IQuerySceneInstService.class).getExtParameterValue(sceneInstId, "batchNodeId"))) {
            kiteAttrs.forEach(kiteAttr -> kiteAttr.setIsEdit(KeyConsts.IFTRUE_F));
        }

        return ErrorConsts.SUCCESS.getResult(kiteAttrs);
    }

    @KiteTransactional
    @ApiOperation(value = "查询经办人信息", notes = "查询经办人信息")
    @PostMapping({"/queryHandlerInfos"})
    public DataResult<List<Map<String, Object>>> queryHandlerInfos(@RequestParam(required = true) String custId) {
        List<Map<String, Object>> handlerInfo = new ArrayList<>();
        String lastTydm = "";
        ICustReceptionService custReceptionService = SpringUtil.getBean(ICustReceptionService.class);
        CuccCustInfoDetailDTO custInfo = custReceptionService.getCustomerInfoNew(custId);

        if (KiteStringUtils.isNotEmpty(custInfo.getOrgCode())) {
            lastTydm = custInfo.getOrgCode().substring(custInfo.getOrgCode().length() - 6);
            String postProvinceNbr = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
            Map<String, Object> map = new HashMap<>();
            map.put("LAST_TYDM", lastTydm);
            map.put("AREA", postProvinceNbr);
            handlerInfo = commonService.queryHandlerInfos(map);
            return ErrorConsts.SUCCESS.getResult(handlerInfo);
        } else {
            return ErrorConsts.SUCCESS.getResult(handlerInfo);
        }
    }

    @KiteTransactional
    @ApiOperation(value = "查询经办人附件信息", notes = "查询经办人附件信息")
    @PostMapping({"/queryHandlerFile"})
    public DataResult<Map<String, Object>> queryHandlerFile(@RequestParam(required = true) String fileKey, @RequestParam(required = true) String sceneInstId) {
        Map<String, Object> handlerFile = commonService.queryHandlerFile(fileKey);
        return ErrorConsts.SUCCESS.getResult(handlerFile);
    }

    @KiteTransactional
    @ApiOperation(value = "保存选中经办人信息", notes = "保存选中经办人信息")
    @PostMapping({"/saveHandlerInfos"})
    public DataResult<List<CommonAttrVO>> saveHandlerInfos(@RequestParam(required = true) Map<String, Object> resultMap) {
        Map value = JSON.parseObject(KiteMapUtils.getString(resultMap, "value"), HashMap.class);
        String querySource = KiteMapUtils.getString(value, "querySource");
        String sceneInstId = KiteMapUtils.getString(resultMap, "sceneInstId");
        // 查询来源 0 手输 1 调接口
        if (KiteStringUtils.equals("1", querySource)) {
            List<CommonAttrVO> commonAttrList = new ArrayList<>();
            if (KiteStringUtils.isEmpty(sceneInstId)) {
                sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
            }
            // 除了经办人名称外，所有属性置灰且不允许编辑
            commonAttrList = commonService.saveHandlerInfos(value, sceneInstId);
            return ErrorConsts.SUCCESS.getResult(commonAttrList);
        } else if (KiteStringUtils.equals("0", querySource)) {
            if (KiteStringUtils.isEmpty(sceneInstId)) {
                sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
            }
            String certName = KiteMapUtils.getString(value, "certName");
            DataResult<Boolean> apply = personAttrDealService
                .apply(sceneInstId, LocalKeyConsts.HANDLER_INFO_NAME, certName, certName, LocalKeyConsts.MODULE_ID_OPERATOR);
            // 根据模块返回对应的属性
            List<CommonAttrVO> commonAttrList = new ArrayList<>();
            String offerInstId = querySceneInstService.getSceneInst(sceneInstId).getRootInstId();
            String offerId = querySceneInstService.getOfferInst(KiteWebContext.getContextNew().getCustId(), offerInstId)
                .getSpecId();
            String objId = OfferCache.get(offerId).getCateId();
            List<KiteAttr> commonAttrsByObjId = querySceneInstService
                .listCommonAttrsByObjIdAndModuleId(sceneInstId, objId, LocalKeyConsts.MODULE_ID_OPERATOR);
            List<KiteAttr> commonAttrs = querySceneInstService.listCommonAttrsByObjIdAndModuleId(sceneInstId, null, LocalKeyConsts.MODULE_ID_OPERATOR);
            if (KiteListUtils.isNotEmpty(commonAttrsByObjId)) {
                commonAttrs.addAll(commonAttrsByObjId);
            }
            List<InstAttrDTO> instAttrDTOList = CopyToDtoUtil.transInstAttrDtoList(commonAttrs);
            if (KiteListUtils.isNotEmpty(instAttrDTOList)) {
                instAttrDTOList.removeIf(
                    instAttrDTO -> !KiteStringUtils.equalsAny(instAttrDTO.getShowType(), KeyConsts.PROD_ATTR_SHOW_TYPE_D, KeyConsts.PROD_ATTR_SHOW_TYPE_M));
                commonAttrList = KiteListUtils.isNotEmpty(instAttrDTOList) ?
                    instAttrDTOList.stream().map(attrDTO -> KiteBeanUtils.transform(attrDTO, CommonAttrVO.class))
                        .collect(Collectors.toList()) :
                    Collections.emptyList();
            }
            return ErrorConsts.SUCCESS.getResult(commonAttrList);
        }
        return ErrorConsts.SUCCESS.getResult(new ArrayList<>());
    }

    @KiteTransactional
    @ApiOperation(value = "查询商机信息(创新头条)", notes = "查询商机信息(创新头条)")
    @PostMapping({"/queryOppoInfos"})
    public DataResult<PageInfo<Map<String, Object>>> queryOppoInfos(@RequestBody(required = true) Map<String, Object> map) {
        PageInfo<Map<String, Object>> queryOppoName = new PageInfo<>();
        queryOppoName = commonService.queryOppoInfos(map);
        return ErrorConsts.SUCCESS.getResult(queryOppoName);
    }

    @KiteTransactional
    @ApiOperation(value = "查询产商品", notes = "查询产商品")
    @PostMapping({"/queryValueList"})
    public DataResult<PageInfo<PropertyValueVO>> queryValueList(@RequestBody(required = true) Map<String, Object> map) {
      /*  Map<String, Object> map =new HashMap();
        map.put("vpnType",vpnType);
        map.put("vpnName",vpnName);
        map.put("vpnCity",vpnCity);
        map.put("commodityCode",commodityCode);
        map.put("skuCode",skuCode);
        map.put("provinceName",provinceName);*/
        PageInfo<PropertyValueVO> pageInfo =commonService.queryValueList(map);
        return ErrorConsts.SUCCESS.getResult(pageInfo);
    }
    @KiteTransactional
    @ApiOperation(value = "新增产商品", notes = "查询产商品")
    @PostMapping({"/insertValueList"})
    public DataResult<String> insertValueList(@RequestBody(required = true) Map<String, Object> map) {
        commonService.insertValueList(map);
        return ErrorConsts.SUCCESS.getResult("1");
    }
    @KiteTransactional
    @ApiOperation(value = "创建产商品", notes = "查询产商品")
    @PostMapping({"/commitValueList"})
    public DataResult<String> commitValueList(@RequestBody(required = true) Map<String, Object> map) {
        commonService.commitValueList(map);
        return ErrorConsts.SUCCESS.getResult("1");
    }
}
